﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMSGSC.BLL;
using PMSGSC.DAL;
using System.Linq;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using PMSGSC.Common;
namespace PMSGSC.App
{
    public partial class frmStockIn : DevExpress.XtraEditors.XtraForm
    {
        public frmStockIn(List<Invoice> invoiceList, frmMain objMain)
        {
            InitializeComponent();
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            stockUnitBindingSource.DataSource = Unit_BLL.GetAll(frmMain.ship.Ship_ID);
            stockBindingSource.DataSource = Stock_BLL.GetAll(frmMain.ship.Ship_ID);
            main = objMain;
            if (invoiceList == null)
            {
                Invoice = invoiceBindingSource.AddNew() as Invoice;
                Invoice.InvoiceCode = "IN" + DateTime.Now.Year + Invoice_BLL.GetOrderNumberVoucherIn();
                Invoice.InvoiceDate = DateTime.Now.Date;
                Invoice.TransType = "Purchase";
                Invoice.Ship_ID = frmMain.ship.Ship_ID;
            }
            else
            {
                invoiceBindingSource.DataSource = invoiceList;
                Invoice = invoiceBindingSource.Current as Invoice;
             
                ucLoadEquipment1.txtCode.Text = Invoice.Equipment.CodeEquipment;
                ucLoadEquipment1.txtName.Text = Invoice.Equipment.NameEquipment;
                ucLoadEquipment1.lbid.Text = Invoice.Equipment_ID.ToString();
                invoiceDetailBindingSource.DataSource = InvoiceDetail_BLL.GetAll(Invoice.Invoice_ID);
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment1.lbid.Text));
            }
        }
        private frmMain main;
        Invoice Invoice;
        InvoiceDetail InvoiceDetail;
        private void pnLeft_SizeChanged(object sender, EventArgs e)
        {
           // ucLoadEquipment1.Width = pnLeft.Width / 2 - 220;
        }

        private void frmStockIn_SizeChanged(object sender, EventArgs e)
        {
            pnBottom.Height = this.Height - pnLeft.Height - txtGhiChu.Height - 40;
            txtGhiChu.Width = this.Width - 50;
        }

        private void PartCode_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (ucLoadEquipment1.lbid.Text != "")
            {
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment1.lbid.Text));
            }
        }

        private void name_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (ucLoadEquipment1.lbid.Text != "")
            {
                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetAll(int.Parse(ucLoadEquipment1.lbid.Text));
            }
        }

        private void code_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((InvoiceDetail)gridView1.GetFocusedRow()).PartsInEquipment= BaseDAL.DB.PartsInEquipments.Single(n => n.Parts_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void name_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((InvoiceDetail)gridView1.GetFocusedRow()).PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(n => n.Parts_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void Stock_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((InvoiceDetail)gridView1.GetFocusedRow()).Stock = BaseDAL.DB.Stocks.Single(n => n.Stock_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void code_EditValueChanged(object sender, EventArgs e)
        {
            GridLookUpEdit gridLookup = sender as GridLookUpEdit;
            gridView1.PostEditor();
            PartsInEquipment part = PartInEquipment_BLL.GetDataById(int.Parse(gridLookup.EditValue.ToString()));
        }

        private void name_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.PostEditor();
        }

        private void btnSaveAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ucLoadEquipment1.lbid.Text == "")
            {
                XtraMessageBox.Show("Please choose component before insert value", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (InvoiceDetail.Stock_ID == null)
            {
                XtraMessageBox.Show("Please choose Stock before insert value", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            SetValueBeforeInsert(Invoice);
            Invoice.Equipment_ID = int.Parse(ucLoadEquipment1.lbid.Text);
            if (Invoice.Invoice_ID == 0)
            {
                Invoice.Type = true;
                Invoice_BLL.Insert(Invoice);
                Invoice = Invoice_BLL.GetNewInvoice();
            }
            else
            {
                Invoice_BLL.Update(Invoice);
            }
            InsertValueIntoInvoiceDetail();
            XtraMessageBox.Show("Insert Success !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void InsertValueIntoInvoiceDetail()
        {
            foreach (InvoiceDetail invoiceDetail in invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList())
            {
                invoiceDetail.Invoice = BaseDAL.DB.Invoices.Single(n => n.Invoice_ID == Invoice.Invoice_ID);
                InvoiceDetail_BLL.Update(invoiceDetail);

                LocationInStock newLocation = LocationInStock_BLL.isExits2(invoiceDetail.Part_ID.Value, invoiceDetail.Stock_ID.Value);
                if (null == newLocation)
                {
                    newLocation = new LocationInStock();
                    newLocation.Parts_ID = invoiceDetail.Part_ID.Value;
                    newLocation.Stock_ID = invoiceDetail.Stock_ID.Value;
                    newLocation.Quantity = invoiceDetail.Quantity.Value;
                    LocationInStock_BLL.Insert(newLocation);
                }
                else
                {
                    newLocation.Quantity += invoiceDetail.Quantity.Value;
                    LocationInStock_BLL.Update(newLocation);
                }
            }
        }
        private void SetValueBeforeInsert(Invoice Invoice)
        {
            if (invoiceDateDateEdit.ContainsFocus)
                Invoice.InvoiceDate = invoiceDateDateEdit.DateTime.Date;
            if (transTypeComboBoxEdit.ContainsFocus)
                Invoice.TransType = transTypeComboBoxEdit.Text;
            if (txtGhiChu.ContainsFocus)
                Invoice.Note = txtGhiChu.Text;
            
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn PartCol = view.Columns["PartCode"];
            GridColumn StockCol = view.Columns["Stock_ID"];

            if (null == view.GetRowCellValue(e.RowHandle, PartCol))
            {
                e.Valid = false;
                view.FocusedColumn = PartCol;
                e.ErrorText = "Please enter the Part. ";
                view.SetColumnError(PartCol, "Part cannot be empty");
                return;
            }

            if (null == PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, PartCol)))
            {
                e.Valid = false;
                view.FocusedColumn = PartCol;
                e.ErrorText = "Please enter the Part. ";
                view.SetColumnError(PartCol, "Part hasn't existed");
                return;
            }

            if (null == view.GetRowCellValue(e.RowHandle, StockCol))
            {
                e.Valid = false;
                view.FocusedColumn = StockCol;
                e.ErrorText = "Please enter the Stock. ";
                view.SetColumnError(StockCol, "Stock cannot be empty");
                return;
            }
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                }
            }
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (Invoice.Invoice_ID != 0)
            {
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));
                thread.Start();
                frmReviewStockIn printStockIn = new frmReviewStockIn(Invoice.Invoice_ID);
                printStockIn.MdiParent = main;
                printStockIn.Show();

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }
        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridColumn QuantityCol = gridView1.Columns["Quantity"];
            if (e.Column == QuantityCol)
            {
                if (e.Value != null)
                {
                    InvoiceDetail.Quantity = int.Parse(e.Value.ToString());
                }
            }
            GridColumn StockCol = gridView1.Columns["Stock_ID"];
            if (e.Column == StockCol)
            {
                if (e.Value != null)
                {
                    InvoiceDetail.Stock = BaseDAL.DB.Stocks.Single(n=>n.Stock_ID ==  int.Parse(e.Value.ToString()));
                }
            }
        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn QuantityCol = view.Columns["Quantity"];
            view.SetFocusedRowCellValue(QuantityCol, 0);
        }

        private void InvoiceDetailBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            InvoiceDetail = invoiceDetailBindingSource.Current as InvoiceDetail;
        }

        private void employee_IDGridLookUpEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                Invoice.Employee = null;
            else
                Invoice.Employee = BaseDAL.DB.Employees.Single(n => n.Employee_ID == (int)e.NewValue);
        }

        private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {

        }

        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Invoice = invoiceBindingSource.AddNew() as Invoice;
            Invoice.InvoiceCode = "IN" + DateTime.Now.Year + Invoice_BLL.GetOrderNumberVoucherIn();
            Invoice.InvoiceDate = DateTime.Now.Date;
            Invoice.TransType = "Purchase";
            Invoice.Ship_ID = frmMain.ship.Ship_ID;
        }

        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }
        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private void btnLoadPart_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmGridPart gridPart = new frmGridPart();
            gridPart.ShowDialog();

            GridView view = gridView1 as GridView;

            if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
            {
                view.AddNewRow();
            }
            if (gridPart.PartsInEquipment != null)
            {
                view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, gridPart.PartsInEquipment.PartCode);
                view.SetRowCellValue(view.FocusedRowHandle, colPartName2, gridPart.PartsInEquipment.PartName);
                view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                InvoiceDetail.PartsInEquipment = gridPart.PartsInEquipment;

                InvoiceDetail.PartCode = gridPart.PartsInEquipment.PartCode;
                InvoiceDetail.PartName = gridPart.PartsInEquipment.PartName;
            }
        }
        private bool flag = false;
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridView view = gridControl1.FocusedView as GridView;
            if (e.Column.FieldName == "PartCode" && flag == false)
            {
                flag = true;
                if (e.Value != null && view.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    PartsInEquipment part;
                    part = PartInEquipment_BLL.GetDataByNumber(view.GetRowCellDisplayText(view.FocusedRowHandle, e.Column));

                    if (part != null)
                    {
                        if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                        {
                            view.AddNewRow();
                        }

                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, part.PartCode);
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName2, part.PartName);
                        view.SetRowCellValue(view.FocusedRowHandle, colQuantity, 0);

                        InvoiceDetail.PartsInEquipment = part;

                        InvoiceDetail.PartCode = part.PartCode;
                        InvoiceDetail.PartName = part.PartName;
                    }
                    else
                    {
                        view.SetColumnError(colPartCode2, "Equipment cannot be empty");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartCode2, "");
                        view.SetRowCellValue(view.FocusedRowHandle, colPartName2, "");
                        InvoiceDetail.PartsInEquipment = null;
                    }
                    flag = false;
                }

            }
        }

    }
}